//
//  StoredViewController
//  DownloadTube
//
//  Created by Carlos on 16/10/14.
//  Copyright (c) 2014 Carlos. All rights reserved.
//

import UIKit
import CoreData
import AVKit
import AVFoundation
import iAd

class StoredViewController: UIViewController, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate, DZNEmptyDataSetSource, ADBannerViewDelegate {

    private var data = []
    private var sortFieldSelected = VideoSorterOptions.Title
    
    private enum VideoSorterOptions {
        
        case Title, Author, TopLength, TopSize, RecentSaved
        static let allValues = [Title, Author, TopLength, TopSize, RecentSaved]
        
        var description : String {
            switch self {
            case .Title: return Utils.localizedString("Title")
            case .Author: return Utils.localizedString("Author")
            case .TopLength: return Utils.localizedString("Top Length")
            case .TopSize: return Utils.localizedString("Top Size")
            case .RecentSaved: return Utils.localizedString("Recent Saved")
            default: return ""
            }
        
        }
    }
    
    @IBOutlet weak var searchBar: UISearchBar!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var sortButton: UIBarButtonItem!
    @IBOutlet weak var seeAllButton: UIBarButtonItem!
    @IBOutlet weak var iADBanner: ADBannerView!
    
    override func viewDidLoad() {

        super.viewDidLoad()
        tableView.estimatedRowHeight = 96.0
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.emptyDataSetSource = self
        tableView.tableFooterView = UIView()
        iADBanner.delegate = self
        iADBanner.alpha = 0
        loadStoredVideos()
        
        lookAndFeel()
    }

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       
        return data.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier("StoredCell", forIndexPath: indexPath) as StoredCell
        let video = data[indexPath.row] as VideoMO
        cell.thumbnail!.image = LookAndFeel.style.loadingImage
        cell.title.text = video.title
        cell.author.text = video.author
        cell.length.text = video.length
        cell.size.text = Utils.localizedString(" %.2f MBs", arguments: [Float(video.spaceOnDisk)/1048576.0])
        cell.format.text = String(format:"%@", Utils.videoQA2.qualities[video.type.integerValue]!.desc)
        var thumbnail:UIImage?
        
        Async.background {
            
            let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
            let pathFile = documentsPath.stringByAppendingPathComponent(video.thumbnailFilename)
            thumbnail = UIImage(contentsOfFile: pathFile)
            
        }.main{
            
            cell.thumbnail!.image = thumbnail
        }
        
        return cell
    }

    func controllerDidChangeContent(controller: NSFetchedResultsController!) {
        
        loadStoredVideos()
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        
        let indexSelected = self.tableView.indexPathForSelectedRow()?.row
        let video = data[indexSelected!] as NSManagedObject
        let playerController:PlayerViewController = segue.destinationViewController as PlayerViewController
        let videoFileName = video.valueForKey("filename")! as String
        let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
        let pathFile = documentsPath.stringByAppendingPathComponent(videoFileName)
        
        playerController.file = pathFile
        
//        var videoItemsToPlay:[AVPlayerItem] = []
//        for video in data {
//            
//            let videoFileName = video.valueForKey("filename")! as String
//            let pathFile = documentsPath.stringByAppendingPathComponent(videoFileName)
//            videoItemsToPlay.append(AVPlayerItem(URL: NSURL(fileURLWithPath: pathFile)))
//        }
//        
//        playerController.items = videoItemsToPlay
        
        
    }
    
    func savedVideo(notification: NSNotification){
        
        loadStoredVideos()
    }
    
    func loadStoredVideos(){
        
        switch(sortFieldSelected){
            
        case .Author: data = VideoDao.sharedInstance.findByTitleOrAuthorOrderByAuthorAsc(searchBar.text)
        case .TopLength: data = VideoDao.sharedInstance.findByTitleOrAuthorOrderByLengthDesc(searchBar.text)
        case .TopSize: data = VideoDao.sharedInstance.findByTitleOrAuthorOrderBySizeDesc(searchBar.text)
        case .RecentSaved: data = VideoDao.sharedInstance.findByTitleOrAuthorOrderBySavedDateDesc(searchBar.text)
        default: data = VideoDao.sharedInstance.findByTitleOrAuthorOrderByTitleAsc(searchBar.text)
            
        }
     
        Async.main {
            
        self.tableView.reloadData()
        
        var totalSpaceOnDisk:Int64 = 0
        for video in self.data {
            
            totalSpaceOnDisk += (video as VideoMO).spaceOnDisk
        }

        
        
            self.subtitle = Utils.localizedString("%d videos. %.2f MBs", arguments: [self.data.count, Float(totalSpaceOnDisk)/1048576.0])
       }
    }
    
   func tableView(tableView: UITableView!, editActionsForRowAtIndexPath indexPath: NSIndexPath!) -> [AnyObject] {
        
        var cancelAction = UITableViewRowAction(style: .Default, title: "Delete") { (action, indexPath) -> Void in
            tableView.editing = false
            
            var alert = UIAlertController(title: Utils.localizedString("Confirm action"), message: Utils.localizedString("Do you really want to delete this item?"), preferredStyle: .Alert)
            
            alert.addAction(UIAlertAction(title: Utils.localizedString("No"), style: .Cancel, handler: nil))
            alert.addAction(UIAlertAction(title: Utils.localizedString("Yes"), style: .Destructive) { (action) in
                
                let storedVideo = self.data[indexPath.row] as NSManagedObject
                let fileManager = NSFileManager.defaultManager()
                let videoFileName = storedVideo.valueForKey("filename")! as String
                let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
                let pathFile = documentsPath.stringByAppendingPathComponent(videoFileName)
                let pathFileThumbnail = documentsPath.stringByAppendingPathComponent(storedVideo.valueForKey("thumbnailFilename")! as String)
                fileManager.removeItemAtPath(pathFileThumbnail, error: nil)
                fileManager.removeItemAtPath(pathFile, error: nil)
                VideoDao.sharedInstance.deleteObject(storedVideo)
                
                self.tableView.beginUpdates()
                self.tableView.deleteRowsAtIndexPaths( [indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
                let aux = self.data.mutableCopy()
                aux.removeObjectAtIndex(indexPath.row)
                self.data = aux as NSArray
                self.tableView.endUpdates()
                self.subtitle = nil
                self.loadStoredVideos()
            })
      
            self.presentViewController(alert, animated: true, completion: nil)
        }
        
        return [cancelAction]
    }

    func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
    }
    
    func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {

        loadStoredVideos()
    }
    
    func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
    
        self.navigationController?.setNavigationBarHidden(true, animated: true)
        changeTitleSearchBarCancelButton()
    }
    
    func searchBarTextDidEndEditing(searchBar: UISearchBar){
  
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    func titleForEmptyDataSet(scrollView:UIScrollView) -> NSAttributedString {
        
        let message = Utils.localizedString("No saved videos")
        return NSAttributedString(string: message, attributes: LookAndFeel.style.titleEmptyViewAttributes)
    }
    
    func descriptionForEmptyDataSet(scrollView:UIScrollView) -> NSAttributedString {
        
        let message = Utils.localizedString("There are not videos in this view")
        return NSAttributedString(string: message, attributes: LookAndFeel.style.descriptionEmptyViewAttributes)
    }
    
    func imageForEmptyDataSet(scrollView:UIScrollView) -> UIImage {
        
        return UIImage(named: "saved-videos-empty-state.png")!.imageByApplyingAlpha(0.7)
    }

//    override func preferredStatusBarStyle() -> UIStatusBarStyle {
//        
//        return UIStatusBarStyle.LightContent
//    }
    
    func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
        
        searchBar.showsCancelButton = true
        return true
    }
    
    func searchBarShouldEndEditing(searchBar: UISearchBar) -> Bool {
        
        searchBar.showsCancelButton = false
        return true
    }
    
    
    func searchBarCancelButtonClicked(searchBar: UISearchBar) {
        
        searchBar.endEditing(true)
    }
    
    func searchBarSearchButtonClicked(searchBar: UISearchBar) {
        
        searchBar.endEditing(true)
    }
    
    func changeTitleSearchBarCancelButton() {
        
        for subView in searchBar.subviews[0].subviews {
    
            if (subView.isKindOfClass(NSClassFromString("UINavigationButton"))) {
 
                subView.setTitle(Utils.localizedString("Done"), forState: .Normal)
                break
            }
        }
    }

    @IBAction func seeAllSavedVideos(){
        
        searchBar.text = ""
        loadStoredVideos()
    }
    
    
    private func lookAndFeel(){
        
        self.view.backgroundColor = LookAndFeel.style.mainColor
    }
    
    @IBAction func sorterStoredVideos(){
        
        var actionSheet =  UIAlertController(title: Utils.localizedString("Sort videos by"), message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
        
        
        for sortOption in VideoSorterOptions.allValues {
        
            actionSheet.addAction(UIAlertAction(title: sortOption != self.sortFieldSelected ? sortOption.description : "[ \(sortOption.description) ]", style: .Default, handler:  {(ACTION :UIAlertAction!) in
                
                if(sortOption != self.sortFieldSelected) {
                    
                    self.sortFieldSelected = sortOption
                    self.loadStoredVideos()
                    self.tableView.setContentOffset(CGPointZero, animated: false)
                }
            }))

        }
        
        actionSheet.addAction(UIAlertAction(title: Utils.localizedString("Cancel"), style: UIAlertActionStyle.Cancel, handler: nil))
        self.presentViewController(actionSheet, animated: true, completion: nil)
    }
    
    func bannerViewDidLoadAd(banner: ADBannerView!){
        
        UIView.animateWithDuration(0.5) {
            
            let iADBannerHeight = self.iADBanner.frame.height
            self.iADBanner.alpha = 1
            self.tableView.contentInset = UIEdgeInsetsMake(0, 0, iADBannerHeight, 0);
        }
    }
    
    func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!){
        
        UIView.animateWithDuration(0.5) {
            
            self.iADBanner.alpha = 0
            self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        }
    }
    
    override func viewWillAppear(animated: Bool) {

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "savedVideo:", name:"FinishedDownload", object: nil)
        loadStoredVideos()
    }
    
    override func viewWillDisappear(animated: Bool) {
        
        NSNotificationCenter.defaultCenter().removeObserver(self, name: "FinishedDownload", object: nil)
    }

}
